package com.chutoutian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chutoutian.mapper.AddressMapper;
import com.chutoutian.mapper.OrdersItemMapper;
import com.chutoutian.mapper.OrdersMapper;
import com.chutoutian.po.Address;
import com.chutoutian.po.Orders;
import com.chutoutian.service.OrdersService;
import com.chutoutian.untils.SnowflakeIdWorker;
import com.chutoutian.vo.OrdersItemVO;
import com.chutoutian.vo.OrdersVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrdersItemMapper ordersItemMapper;

    @Resource
    private AddressMapper addressMapper;

    @Override
    public List<OrdersVO> findVO(Orders bean) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>(bean);
        List<Orders> ordersList = ordersMapper.selectList(queryWrapper);

        List<OrdersVO> result = new ArrayList<>();
        for (Orders item : ordersList) {
            OrdersVO ordersVO = new OrdersVO(item);
            List<OrdersItemVO> ordersItemVOList = ordersItemMapper.findVO(ordersVO.getId());
            ordersVO.setOrdersItemVOList(ordersItemVOList);
            result.add(ordersVO);
        }
        return result;
    }

    @Override
    public OrdersVO getVO(String id) {

        Orders orders = ordersMapper.selectById(id);
        OrdersVO result = new OrdersVO(orders);
        Address address = addressMapper.selectById(result.getAddressId());
        result.setAddress(address);
        List<OrdersItemVO> ordersItemVOList = ordersItemMapper.findVO(result.getId());
        result.setOrdersItemVOList(ordersItemVOList);
        return result;
    }

    @Override
    public void add(Orders orders) {
        orders.setId(SnowflakeIdWorker.getId());
        orders.setCreateTime(new Date());
        ordersMapper.insert(orders);
    }

    @Override
    public Orders get(String id) {
        return ordersMapper.selectById(id);
    }

    @Override
    public void update(Orders orders) {
        orders.setModifiedTime(new Date());
        ordersMapper.updateById(orders);
    }

    @Override
    public void delete(String id) {
        ordersMapper.deleteById(id);
    }

}
